package com.project.genesis.common.util;

import cn.hutool.json.XML;
import com.alibaba.fastjson.JSONObject;
import com.project.genesis.bo.GetWebServiceReq;
import org.apache.commons.lang3.StringEscapeUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class SoapUtil {

    // 定义参数
    public static final String URL_PATH = "http://172.25.29.84:8089/PaoVisitWebService.asmx";
    public static final String TERM = "QryLabExamAppJC";

    public static String createSoapXml(String patientCode){
        String xmlData =
                "        <Req>\n" +
                        "<TransactionCode>7001</TransactionCode>\n" +
                        "<Service>\n" +
                        "<PatientID>"+patientCode+"</PatientID>\n" +
                        "<ZYNo></ZYNo>\n" +
                        " <CliniccardID></CliniccardID>" +
                        "<StartDate></StartDate>" +
                        "<EndDate></EndDate>" +
                        "<PacsStudyuniqueid></PacsStudyuniqueid>" +
                        "<VisitNo></VisitNo>" +
                        "</Service>\n" +
                        "</Req>";
        return xmlData;
    }

    public static JSONObject getInspect(String urlPath, String xmlData, String term) throws IOException {
        // 调用webService查询数据
        String webServiceResult = getWebServiceResult(urlPath, xmlData, term);
        String result = StringEscapeUtils.unescapeXml(webServiceResult);
        String entries = XML.toJSONObject(result).toString();
        String substring = entries.substring(entries.indexOf(":") + 1);
        String str = substring.substring(0, substring.length()-1);
        System.out.println(str);
        JSONObject jsonObject = JSONObject.parseObject(str);
        return jsonObject;
    }


    public static String getWebServiceResult(String urlPath, String testWebService, String term) throws IOException {
        URL url = new URL(urlPath);
        GetWebServiceReq getWebSq = new GetWebServiceReq();
        getWebSq.setUrl(url);
        getWebSq.setTerm(term);
        getWebSq.setJsonObject(testWebService);
        String result = getWebServiceInfo(getWebSq);
        return result;
    }


    public static String getWebServiceInfo(GetWebServiceReq getWebServiceReq) throws IOException {


        try {
            String result = "";

            //第一步：创建服务地址
            //第二步：打开一个通向服务地址的连接
            HttpURLConnection connection = (HttpURLConnection) getWebServiceReq.getUrl().openConnection();
            //第三步：设置参数
            //3.1发送方式设置：POST必须大写
            connection.setRequestMethod("POST");
            //3.2设置数据格式：content-type
            connection.setRequestProperty("content-type", "text/xml;charset=utf-8");
            //3.3设置输入输出，因为默认新创建的connection没有读写权限，
            connection.setDoInput(true);
            connection.setDoOutput(true);

            //第四步：组织SOAP数据，发送请求
            String soapXML = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\">" +
                    "<soapenv:Header/>" +
                    "<soapenv:Body>" +
                    "<tem:" + getWebServiceReq.getTerm() + ">" +
                    "<tem:strxml><![CDATA[" +
                    getWebServiceReq.getJsonObject() +
                    "]]></tem:strxml>" +
                    "</tem:" + getWebServiceReq.getTerm() + ">" +
                    "</soapenv:Body>" +
                    "</soapenv:Envelope>";


            OutputStream os = connection.getOutputStream();
            os.write(soapXML.getBytes());
            //第五步：接收服务端响应，打印
            int responseCode = connection.getResponseCode();
            if (responseCode == 200) {
                InputStream is = connection.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, "UTF-8");
                BufferedReader br = new BufferedReader(isr);
                StringBuilder sb = new StringBuilder();
                String temp = null;
                while (null != (temp = br.readLine())) {
                    sb.append(temp);
                }
                String value = sb.toString().replace("<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">", "")
                        .replace("<soap:Body>", "")
                        .replace("</soap:Body>", "")
                        .replace("</soap:Envelope>", "");


                result = value;
                /**
                 * 打印结果
                 */
                is.close();
                isr.close();
                br.close();

            } else {

            }
            return result;
        } catch (Exception e) {

            throw e;
        }
    }

}